package com.jeeplus.modules.api;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeeplus.common.utils.number.RandomUtil;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.api.res.ResJson;
import com.jeeplus.modules.api.utils.AliOSSUtil;

/**
 * 上传图片
 * 
 * @author mall
 *
 */
@CrossOrigin(origins = "*")
@Controller
@RequestMapping(value = "/api")
public class UploadController extends BaseController {
	
	@PostMapping("/uploadFile")
	@ResponseBody
	public ResJson uploadImage(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		ResJson res = new ResJson();
		res.setResultNote("上传失败");
		try {
			String myFileName = file.getOriginalFilename();
			String ext = myFileName.substring(myFileName.lastIndexOf(".")).toLowerCase();
			String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtil.randomNumberFixLength(4) + ext;
			AliOSSUtil.upload(file.getInputStream(), fileName);
			res.put("url", AliOSSUtil.url + fileName);
			res.setResult("0");
			res.setResultNote("上传成功");
			/*
			Calendar cal = Calendar.getInstance();
	        int year = cal.get(Calendar.YEAR);
	        int month = cal.get(Calendar.MONTH ) + 1;
			String fileUrl = Servlets.getRequest().getContextPath() + Global.USERFILES_BASE_URL  + "files/" + year + "/" + month + "/";
			String fileDir = Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + "files/" + year + "/" + month + "/";
			// 判断文件是否为空
			if (!file.isEmpty()) {
				// 文件保存路径
				// 转存文件
				FileUtils.createDirectory(fileDir);
				String myFileName = file.getOriginalFilename();
				String ext = myFileName.substring(myFileName.lastIndexOf(".")).toLowerCase();
				String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtil.randomNumberFixLength(4) + ext;
				String filePath = fileDir + fileName;
				File newFile = FileUtils.getAvailableFile(filePath,0);
				file.transferTo(newFile);
				
				res.put("url", fileUrl+ newFile.getName());
				res.setResult("0");
				res.setResultNote("上传成功");
			}*/
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		//logger.info("发：" + JSONObject.toJSONString(res));
		return res;
	}
}
